define(function(require, exports, module) {
    var angular = require('angular');
    require("@yunke/jquery_pagination");
    require('angular-ui');
    require("../../../plugins/select2/select2");
    require('../contract-common');
    require('../contract-menu-view');
    var myMath = require('../../common/my-math');
    var dialog = require('@yunke/art-dialog').default;
    var util = require('@yunke/core/util').default;
    var api_prefix = G_CONFIG["api_prefix"]; //api前缀
    var side = require('../../side');
    var moment = require('moment');

    angular.module('ContractBase', ['select2', 'ngUI', 'ContractCommonService', 'ContractMenu'])
        .filter('sumProductAmount', function() {
            return function(products) {
                var amount = 0;
                $.each(products, function(i, d) {
                    if (d.__type == 'delete') {
                        return;
                    }
                    amount = myMath.add(amount, d.amount);
                });
                return amount;
            };
        })
        .filter('shareAmount', ['$filter', function($filter) {
            return function(product, products, rentAmount) {
                var productAmount = $filter('sumProductAmount')(products);

                //（标准总额/产品标准总额合计）*产品租用金额
                if (productAmount == 0) {
                    return 0;
                }

                return (product.amount / productAmount) * rentAmount;
            };
        }])
        .filter('countSMS', function() {
            return function(products) {
                var num = 0;
                $.each(products, function(i, d) {
                    if (d.__type == 'delete') {
                        return;
                    }
                    num = myMath.add(num, d.authorization_type == 1 ? d.authorization_numeric : 0);
                });
                return num;
            };
        })
        .filter('countProject', function() {
            return function(products) {
                var num = 0;
                $.each(products, function(i, d) {
                    if (d.__type == 'delete') {
                        return;
                    }
                    num = myMath.add(num, d.authorization_type == 0 ? d.authorization_numeric : 0);
                });
                return num;
            };
        })
        .filter('getContractTypeName', function() {
            return function(contractType) {
                contractType = parseInt(contractType);
                var name = "";
                switch (contractType) {
                    case 1:
                        name = "新增";
                        break;
                    case 2:
                        name = "增购";
                        break;
                    case 3:
                        name = "续签";
                        break;
                    default:
                        name = ""
                }
                return name;
            };
        })
        .controller('contractBaseCtrl', ['$scope', '$timeout', '$location', '$routeParams', 'contractCommonService', 'contractMenuService', function($scope, $timeout, $location, $routeParams, contractCommonService, contractMenuService) {
            //合同基本信息
            $scope.contractBaseInfo = {
                customer_property: 0,
                attribute_name: "false,false,false",
                contract_status: 0,
                isLimitContractNature: false,
                is_cancelled: 0,
                give_work_day: 0,
                develop_work_day: 0,
                implement_work_day: 0
            };

            //产品列表
            $scope.projects = [];


            //先加载下拉框
            // 合同性质下拉框处理
            $scope.ddlConfigContractNature = {
                allowClear: false,
                data: [],
                placeholder: '合同性质',
                onchange2: function(selected) {
                    //获取公司下拉信息
                    contractCommonService.actionGetContractCompanyList(selected.id, function(data) {
                        var ddlData = [];
                        var isCompanyValid = false;
                        $.each(data, function(i, d) {
                            ddlData.push({
                                id: d.company_id,
                                text: d.company_name
                            });
                            if (d.company_id == $scope.contractBaseInfo.company_id) {
                                isCompanyValid = true;
                            }
                        });
                        $scope.ddlConfigCompany.data = ddlData;
                        if (!isCompanyValid) {
                            //切换性质时清空签署公司
                            $scope.contractBaseInfo.company_id = null;
                        }

                        $scope.$applyAsync();
                    });
                    //若直属区域 ,增加交付信息 菜单
                    //contractMenuService.menuInit(selected.id);
                    //绑定签约金额和收入金额
                    incomeWithSign(selected.id);

                }
            };

            //获取合同性质列表
            contractCommonService.getContractNatures(function(data) {
                var ddlData = [];
                //隐藏 明源签约-联营区域:7f828b1b-fce8-11e4-bed8-00155d02c832,
                //    联营签约-明源结算:7f84cfad-fce8-11e4-bed8-00155d02c832
                $.each(data, function(i, d) {
                    if (d.property_id != '7f84cfad-fce8-11e4-bed8-00155d02c832') {
                        ddlData.push({
                            id: d.property_id,
                            text: d.property_name
                        });
                    }

                });
                $scope.ddlConfigContractNature.data = ddlData;
                $scope.$applyAsync();
            });


            // 合同签署公司下拉框处理
            $scope.ddlConfigCompany = {
                allowClear: false,
                data: [{
                    id: 1,
                    text: '明源云客'
                }],
                placeholder: '合同签署公司'
            };

            // 合同类别下拉框处理
            $scope.ddlConfigContractCategory = {
                allowClear: false,
                data: [{
                    id: 1,
                    text: '云客租用服务合同'
                }],
                placeholder: '合同类别'
            };

            //获取类别下拉信息
            contractCommonService.getContractCategories(function(data) {
                var ddlData = [];
                $.each(data, function(i, d) {
                    ddlData.push({
                        id: d.category_id,
                        text: d.category_name
                    });
                });
                $scope.ddlConfigContractCategory.data = ddlData;
                $scope.$applyAsync();
            });


            // 合同小类下拉框处理
            $scope.ddlConfigContractSmallClass = {
                allowClear: false,
                data: [],
                placeholder: '合同小类'
            };

            // 合同大类下拉框处理
            $scope.ddlConfigContractBigClass = {
                allowClear: false,
                data: [],
                placeholder: '合同大类',
                onchange2: function(item) {
                    if (!item || !item.id) {
                        return;
                    }
                    contractCommonService.getContractSmallClass(item.id, function(data) {
                        var ddlData = [];
                        var curSmallClass = null;
                        $.each(data, function(i, d) {
                            ddlData.push({
                                id: d.littler_category_id,
                                text: d.littler_category_name
                            });
                            if (d.littler_category_id == $scope.contractBaseInfo.littler_category_id) {
                                curSmallClass = {
                                    id: d.littler_category_id,
                                    text: d.littler_category_name
                                };
                            }
                        });
                        $scope.ddlConfigContractSmallClass.data = ddlData;

                        $scope.$applyAsync();
                        setTimeout(function() {
                            $('#idSmallClass').length && $('#idSmallClass').data('select2').updateSelection(curSmallClass);
                        }, 0);

                    })
                }
            };

            //获取大类下拉信息
            contractCommonService.getContractBigClass(function(data) {
                var ddlData = [];
                $.each(data, function(i, d) {
                    ddlData.push({
                        id: d.big_category_id,
                        text: d.big_category_name
                    });
                });
                $scope.ddlConfigContractBigClass.data = ddlData;
                $scope.$applyAsync();
            });

            // 合同签约地区下拉框处理
            $scope.ddlConfigContractSignArea = {
                allowClear: false,
                data: [{
                    id: 1,
                    text: '北京'
                }],
                placeholder: '合同签约地区'
            };
            //获取签约地区下拉信息
            contractCommonService.getContractAreas(function(data) {
                var ddlData = [];
                $.each(data, function(i, d) {
                    ddlData.push({
                        id: d.regionId,
                        text: d.regionName
                    });
                });
                $scope.ddlConfigContractSignArea.data = ddlData;
                $scope.$applyAsync();
            });

            // 产品下拉框数据
            $scope.ddlConfigProjectsData = [];
            //合同主责人下拉数据
            $scope.ddlConfigPrincipalsData = [];
            // 其他产品下拉框数据
            $scope.ddlConfigOtherProjectsData = [];

            //获取产品下拉信息
            contractCommonService.getProducts(function(data) {
                var ddlData = [];
                $.each(data, function(i, d) {
                    ddlData.push($.extend({}, {
                        id: d.application_id,
                        text: d.application_name
                    }, d));
                });
                $scope.ddlConfigProjectsData = ddlData;
            });

            //获取其他产品下拉信息
            contractCommonService.getOtherProducts(function(data) {
                var ddlData = [];
                $.each(data, function(i, d) {
                    ddlData.push($.extend({}, {
                        id: d.application_id,
                        text: d.application_name
                    }, d));
                });
                $scope.ddlConfigOtherProjectsData = ddlData;
            });


            //默认合同属性
            $scope.attribute_name_text = ['新增', '混签', '续签', '增购'];
            $scope.attribute_name_arr = ["false", "false", "false", "false"];
            //合同主责人
            $scope.principals = [];
            $scope.showPrincipal = false;

            // 合同性质为
            // “联营签约-云客结算" 7f856e81-fce8-11e4-bed8-00155d02c832
            // "云客签约-联营区域” 7f8422d0-fce8-11e4-bed8-00155d02c832
            // 合同主责人界面隐藏不显示；
            var notShowPrincipalByContractArr = ['7f856e81-fce8-11e4-bed8-00155d02c832', '7f8422d0-fce8-11e4-bed8-00155d02c832'];

            //默认合同性质  联营签约-云客结算
            if ($scope.contractBaseInfo.contract_property_id == null) {
                $scope.contractBaseInfo.contract_property_id = "7f856e81-fce8-11e4-bed8-00155d02c832";
            }
            //默认合同类型
            if ($scope.contractBaseInfo.category_id == null) {
                $scope.contractBaseInfo.category_id = "b011f523-fcf2-11e4-bed8-00155d02c832";
            }
            //默认合同大类
            if ($scope.contractBaseInfo.big_category_id == null) {
                $scope.contractBaseInfo.big_category_id = "2ae79470-fcf3-11e4-bed8-00155d02c832";
            }
            //默认小类
            if ($scope.contractBaseInfo.littler_category_id == null) {
                $scope.contractBaseInfo.littler_category_id = "62f81bf4-fcf4-11e4-bed8-00155d02c832";
            }

            //获取合同信息
            $scope.loadContract = function(contractId) {
                if (contractId) {
                    contractCommonService.getContract(contractId, function(data) {
                        setTimeout(function() {

                            $scope.contractBaseInfo = data.contract;

                            incomeWithSign(contractId);

                            if ($scope.contractBaseInfo.attribute_name == null) {
                                $scope.contractBaseInfo.attribute_name = "false,false,false,false";
                            }

                            $scope.attribute_name_arr = $scope.contractBaseInfo.attribute_name.split(',');

                            $scope.projects = data.application;
                            $.each($scope.projects, function(i, project) {
                                project.discount_rate = parseFloat(project.discount_rate);
                            })

                            $scope.principals = data.principal;

                            //隐藏合同主责人
                            if (data.contract.contract_property_id != notShowPrincipalByContractArr[0] && data.contract.contract_property_id != notShowPrincipalByContractArr[1]) {
                                $scope.showPrincipal = true;
                            }


                            if (data.contract) {
                                $scope.contractBaseInfo.contract_code_readonly = data.contract.contract_code;
                            }
                            $('#idCustomerName').length && $('#idCustomerName').data('select2').updateSelection({
                                text: data.contract.customer_name || ''
                            });
                            $('#idSigner').length && $('#idSigner').data('select2').updateSelection({
                                text: data.contract.sign_people_name || data.contract.sign_people_id
                            });
                            $('#idCompanyId').length && $('#idCompanyId').data('select2').updateSelection({
                                text: data.contract.company_name || ''
                            });
                            var signDate = moment(data.contract.sign_date, 'YYYY-MM-DD HH:mm:ss');
                            if (signDate.isValid()) {
                                $scope.contractBaseInfo.sign_date = signDate.format('YYYY-MM-DD');
                            }
                            var inputDate = moment(data.contract.input_date, 'YYYY-MM-DD HH:mm:ss');
                            if (inputDate.isValid()) {
                                $scope.contractBaseInfo.input_date = inputDate.format('YYYY-MM-DD');
                            }
                            var effect_date = moment(data.contract.effect_date, 'YYYY-MM-DD HH:mm:ss');
                            if (effect_date.isValid()) {
                                $scope.contractBaseInfo.effect_date = effect_date.format('YYYY-MM-DD');
                            }
                            $scope.$applyAsync();
                        }, 500);

                    });
                }
            };


            var contractId = $routeParams.id;
            var fromContractId = $routeParams.pid;
            if (contractId) {
                //编辑模式先设为只读（复核状态），避免复核的合同先显示编辑按钮再隐藏导致的刷新
                $scope.contractBaseInfo.contract_status = 1;
                $scope.loadContract(contractId);
            } else if (fromContractId) {
                contractCommonService.getContract(fromContractId, function(data) {
                    setTimeout(function() {
                        $scope.contractBaseInfo = angular.extend(data.contract, {
                            contract_id: null,
                            contract_code: null,
                            input_date: null,
                            balance_status: 0,
                            is_violated: 0,
                            contract_status: 0,
                            is_cancelled: 0
                        });
                        if (data.application) {
                            $.each(data.application, function(i, d) {
                                d['__type'] = 'add';
                            })
                        }
                        $scope.projects = data.application;


                        $('#idCustomerName').length && $('#idCustomerName').data('select2').updateSelection({
                            text: data.contract.customer_name || ''
                        });
                        $('#idSigner').length && $('#idSigner').data('select2').updateSelection({
                            text: data.contract.sign_people_name || data.contract.sign_people_id
                        });
                        $('#idCompanyId').length && $('#idCompanyId').data('select2').updateSelection({
                            text: data.contract.company_name || ''
                        });
                        $scope.generalContractCode();
                        var signDate = moment(data.contract.sign_date, 'YYYY-MM-DD HH:mm:ss');
                        if (signDate.isValid()) {
                            $scope.contractBaseInfo.sign_date = signDate.format('YYYY-MM-DD');
                        }
                        var inputDate = moment(data.contract.input_date, 'YYYY-MM-DD HH:mm:ss');
                        if (inputDate.isValid()) {
                            $scope.contractBaseInfo.input_date = inputDate.format('YYYY-MM-DD');
                        }
                        $scope.$applyAsync();
                    }, 500);

                });
            }

            /**
             * 合同性质为云客签约-直属区域/云客签约-联营区域 时候
             * 签约金额 = 收入金额
             * @param contractNature  合同性质
             */

            function incomeWithSign(contractNature) {
                //云客签约-直属区域/云客签约-联营区域/云客直销
                var limitContractArr = ['7f83719a-fce8-11e4-bed8-00155d02c832', '7f8422d0-fce8-11e4-bed8-00155d02c832', 'efa353cd-51ca-11e8-a035-00155d02c83e'];

                if (contractNature == limitContractArr[0] || contractNature == limitContractArr[1] || contractNature == limitContractArr[2]) {
                    //把签约金额 复制给 收入金额
                    $scope.contractBaseInfo.income_amount = $scope.contractBaseInfo.sign_amount;
                    //锁定收入金额
                    $scope.contractBaseInfo.isLimitContractNature = true;
                    //监听签约金额
                    $scope.$watch('contractBaseInfo.sign_amount', function(signVal) {
                        $scope.contractBaseInfo.income_amount = signVal;
                    });
                } else {
                    $scope.contractBaseInfo.isLimitContractNature = false;
                }
            }


            // 客户下拉框处理
            $scope.ddlConfigCustomer = {
                allowClear: false,
                placeholder: '客户简称',
                ajax: {
                    url: api_prefix + "erp-interface/get-erp-customer-info",
                    dataType: 'json',
                    delay: 250,
                    data: function(term) {
                        return {
                            keyword: term,
                            limit: 10
                        };
                    },
                    results: function(json, page) {
                        var data = [];
                        if (json.retCode === "0") {
                            data = json.data;
                            $.each(data, function(i, d) {
                                d.text = d.CstName;
                                d.id = d.CSTGUID;
                            });
                        }
                        return {
                            results: data
                        };
                    },
                    cache: true
                },
                escapeMarkup: function(markup) {
                    return markup;
                },
                minimumInputLength: 1,
                onchange2: function(newVal) {
                    $scope.contractBaseInfo.top_customer_name = newVal.DjCstName;
                    $scope.contractBaseInfo.customer_full_name = newVal.CstFullName;
                    $scope.contractBaseInfo.customer_name = newVal.CstName;
                    $scope.contractBaseInfo.customer_code = newVal.CstShortCode;
                },
                formatResult: formatCustomer,
                formatSelection: formatCustomerSelection // omitted for brevity, see the source of this page
            };

            function formatCustomer(repo) {
                if (repo.loading) return repo.text;

                return repo.text;
            }

            function formatCustomerSelection(repo) {
                return repo.text;
            }

            // 合同签约人下拉框处理
            $scope.ddlConfigContractSigner = {
                allowClear: false,
                ajax: {
                    url: api_prefix + "erp-interface/get-users",
                    dataType: 'json',
                    delay: 250,
                    data: function(term) {
                        return {
                            keyword: term,
                            limit: 10
                        };
                    },
                    results: function(json, page) {
                        var data = [];
                        if (json.retCode === "0") {
                            data = json.data;
                        }
                        return {
                            results: data
                        };
                    },
                    processResults: function(data, page) {
                        // parse the results into the format expected by Select2.
                        // since we are using custom formatting functions we do not need to
                        // alter the remote JSON data
                        return {
                            results: data.items
                        };
                    },
                    cache: true
                },
                escapeMarkup: function(markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 1,
                onchange2: function(newVal) {
                    $scope.contractBaseInfo.area_name = newVal.BUName;
                    $scope.contractBaseInfo.area_id = newVal.BUGUID;
                    $scope.contractBaseInfo.area_code = newVal.BUCode;
                    $scope.contractBaseInfo.sign_people_department_name = newVal.DepartmentName;
                    $scope.contractBaseInfo.sign_people_department_by = newVal.DepartmentId;
                    $scope.contractBaseInfo.sign_people_abu_name = newVal.AubName;

                    $scope.contractBaseInfo.sign_people_id = newVal.UserGUID;
                    $scope.contractBaseInfo.sign_people_name = newVal.UserName;
                },
                formatResult: formatRepo,
                formatSelection: formatRepoSelection // omitted for brevity, see the source of this page
            };

            function formatRepo(repo) {
                if (repo.loading) return repo.text;

                var markup = '<div class="clearfix" style="width: 300px;">' +
                    '<div class="clearfix">' +
                    '<div class="col-sm-6">' + repo.UserName + '</div>' +
                    '<div class="col-sm-18">' + repo.BUName + '</div>' +
                    '</div></div>';

                return markup;
            }

            function formatRepoSelection(repo) {
                return repo.text;
            }

            $scope.ddl2Customer = '';
            $scope.ddl2Type = '';
            $scope.ddl2Company = '';
            $scope.ddl2Category = '';
            $scope.ddl2BigClass = '';
            $scope.ddl2SmallClass = '';
            $scope.ddl2Signer = '';
            $scope.ddl2SignArea = '';
            $scope.ddl2Nature = '';

            function formatProduct(repo) {
                if (repo.loading) return repo.text;

                var markup = '<div class="clearfix">' +
                    '<div class="clearfix">' +
                    '<div class="col-sm-24">' + repo.application_name + '</div>' +
                    '</div></div>';

                return markup;
            }

            function formatProductSelection(repo) {
                return repo.application_name;
            }

            //新增/修改产品
            $scope.onProductEditShow = function($data, $dialog, $dialogScope, oldProd) {
                $dialogScope.oldProd = oldProd;
                if (!$dialogScope.data.discount_rate) {
                    $dialogScope.data.discount_rate = 1;
                }
                //项目数
                $dialogScope.$watch('data.authorization_numeric', function(itemVal) {
                    if ($dialogScope.data.authorization_type == 0 && $dialogScope.data.unique_name!="ad") {
                        var period = $dialogScope.data.rent_period || 0;
                        var discount = parseFloat($dialogScope.data.discount_rate) || 1;
                        $dialogScope.data.amount = Math.round(myMath.div(myMath.mul(myMath.mul(myMath.mul(itemVal, period), discount), $dialogScope.data.price), 12));
                    }
                });
                //项目周期
                $dialogScope.$watch('data.rent_period', function(itemVal) {
                    if ($dialogScope.data.authorization_type == 0 && $dialogScope.data.unique_name!="ad") {
                        var number = $dialogScope.data.authorization_numeric || 0;
                        var discount = parseFloat($dialogScope.data.discount_rate) || 1;
                        $dialogScope.data.amount = Math.round(myMath.div(myMath.mul(myMath.mul(myMath.mul(itemVal, number), discount), $dialogScope.data.price), 12));
                    }
                });
                /*
                //折扣率
                $dialogScope.$watch('data.discount_rate', function(itemVal) {
                    if ($dialogScope.data.authorization_type == 0) {
                        var discountRate = document.getElementById("inputDiscount");
                        $dialogScope.data.contrLen = discountRate.value.length;
                        if (discountRate.value.length > 10) {
                            discountRate.value = discountRate.value.substr(0, 9);
                        }
                        var period = $dialogScope.data.rent_period || 0;
                        var number = $dialogScope.data.authorization_numeric || 0;
                        $dialogScope.data.amount = Math.round(myMath.div(myMath.mul(myMath.mul(myMath.mul(itemVal, number), period), $dialogScope.data.price), 12));
                    }
                });
                */
                //免费短信金额为0，不允许修改
                $dialogScope.$watch('data.price', function(itemVal) {
                    if (parseFloat(itemVal) == 0) {
                        $dialogScope.data.amount = 0;
                    }
                    if($dialogScope.data.application_id=="other"){
                      var number = $dialogScope.data.authorization_numeric || 0;
                      var period = $dialogScope.data.rent_period || 0;
                      $dialogScope.data.amount = Math.round(myMath.div(myMath.mul(myMath.mul(myMath.mul(number, period), 1), itemVal), 12));
                    }
                })

                ////合同属性
                const contractTypeData = [{
                    "id": 1,
                    "text": "新增"
                }, {
                    "id": 2,
                    "text": "增购"
                }, {
                    "id": 3,
                    "text": "续签"
                }];
                $dialogScope.ddlConfigContractType = {
                    allowClear: false,
                    data: contractTypeData,
                    placeholder: '合同属性',
                    onchange2: function(contractType) {
                        $dialogScope.data.contract_type = contractType.id;
                    }
                };

                //如果是新增，合同属性取基本信息中的
                if(oldProd==undefined){
                    //合同属性
                    var isXz= $scope.attribute_name_arr[0]=="true" ? true : false;
                    var isHq= $scope.attribute_name_arr[1]=="true" ? true : false;
                    var isXq= $scope.attribute_name_arr[2]=="true" ? true : false;
                    var isZg= false;
                    if($scope.attribute_name_arr.length==4){
                      isZg=$scope.attribute_name_arr[3]=="true" ? true : false;
                    }
                    if(isXz && !isHq && !isXq && !isZg) {
                      $dialogScope.data.contract_type=1;
                    }
                    if(!isXz && !isHq && !isXq && isZg) {
                      $dialogScope.data.contract_type=2;
                    }
                    if(!isXz && !isHq && isXq && !isZg) {
                      $dialogScope.data.contract_type=3;
                    }
                }

                $dialogScope.ddlConfigProjects = {
                    allowClear: false,
                    data: $scope.ddlConfigProjectsData,
                    placeholder: '产品名称',
                    onchange2: function(item) {
                        $dialogScope.data.authorization_type = item.authorization_type;
                        $dialogScope.data.application_name = item.application_name;
                        $dialogScope.data.application_id = item.application_id;
                        $dialogScope.data.unique_name = item.unique_name;

                        if (item.authorization_type == 0 && item.applicationPrices.length) {
                            $dialogScope.data.price = item.applicationPrices[0].price;
                            var period = $dialogScope.data.rent_period || 0;
                            var discount = parseFloat($dialogScope.data.discount_rate) || 1;
                            $dialogScope.data.amount = Math.round(myMath.div(myMath.mul(myMath.mul(myMath.mul($dialogScope.data.authorization_numeric, period), discount), $dialogScope.data.price), 12));
                        }

                        var appPrices = [];
                        $.each(item.applicationPrices || [], function(i, d) {
                            appPrices.push({
                                id: d.price,
                                text: d.unit
                            });
                        });

                        $dialogScope.ddlConfigSMSPrice = {
                            allowClear: false,
                            data: appPrices,
                            placeholder: '标准单价',
                            onchange2: function(price) {
                                $dialogScope.data.unit = price.text;
                            }
                        };

                        $dialogScope.$applyAsync();

                    }
                };

              //产品明细
              $dialogScope.ddlConfigOtherProjects={
                allowClear: false,
                data: $scope.ddlConfigOtherProjectsData,
                placeholder: '其他产品',
                onchange2: function(item) {
                  $dialogScope.data.other_application_name = item.application_name;
                  $dialogScope.data.other_application_id = item.application_id
                }
              };

            };
            $scope.addContractProduct = function($data, $dialog, $dialogScope) {
                $scope.projects.push($.extend({
                    __type: 'add',
                    is_standard: '1'
                }, $data));
            };
            $scope.saveContractProduct = function($data, $dialog, $dialogScope) {
                angular.extend($dialogScope.oldProd, $.extend({
                    __type: 'update'
                }, $data));
            };
            $scope.delProject = function(proj) {
                /**
                 * 删除产品
                 */
                utils.confirm('确定要删除此产品吗？', {
                    ok: function() {
                        angular.extend(proj, {
                            __type: 'delete'
                        });
                        $scope.$applyAsync();
                    }
                });

            };


            //新增/修改 合同主责人
            $scope.onPrincipalEditShow = function($data, $dialog, $dialogScope, oldPrinp) {

                //修改模式下 填充合同主责人;
                if ($data) {
                    setTimeout(function() {
                        $(".principalBy").select2("data", {
                            id: $data.principal_by,
                            text: $data.principal_name
                        });
                    }, 0);

                } else {
                    //默认合同签约人
                    setTimeout(function() {
                        $(".principalBy").select2("data", {
                            id: $scope.contractBaseInfo.sign_people_id,
                            text: $scope.contractBaseInfo.sign_people_name
                        });
                    }, 0);


                    $dialogScope.data.principal_abu_name = $scope.contractBaseInfo.sign_people_abu_name;
                    $dialogScope.data.principal_department_name = $scope.contractBaseInfo.sign_people_department_name;
                    $dialogScope.data.principal_area_name = $scope.contractBaseInfo.area_name;

                    $dialogScope.data.principal_department_by = $scope.contractBaseInfo.sign_people_department_by;
                    $dialogScope.data.principal_area_by = $scope.contractBaseInfo.area_id;

                    $dialogScope.data.principal_by = $scope.contractBaseInfo.sign_people_id;
                    $dialogScope.data.principal_name = $scope.contractBaseInfo.sign_people_name;

                    $dialogScope.data.principal_on = contractCommonService.getCurTime();

                    $dialogScope.data.principal_remark = '合同签约人';


                }


                $dialogScope.oldPrinp = oldPrinp;
                //主责人 下拉框处理
                $dialogScope.ddlConfigPrincipal = {
                    allowClear: false,
                    ajax: {
                        url: api_prefix + "erp-interface/get-users",
                        dataType: 'json',
                        delay: 250,
                        data: function(term) {
                            return {
                                keyword: term,
                                limit: 10
                            };
                        },
                        results: function(json, page) {
                            var data = [];
                            if (json.retCode === "0") {
                                data = json.data;
                            }
                            return {
                                results: data
                            };
                        },
                        processResults: function(data, page) {
                            // parse the results into the format expected by Select2.
                            // since we are using custom formatting functions we do not need to
                            // alter the remote JSON data
                            return {
                                results: data.items
                            };
                        },
                        cache: true
                    },
                    escapeMarkup: function(markup) {
                        return markup;
                    }, // let our custom formatter work
                    minimumInputLength: 1,
                    onchange2: function(newVal) {
                            $dialogScope.data.principal_abu_by = newVal.AubGUID;
                            $dialogScope.data.principal_abu_name = newVal.AubName;
                            $dialogScope.data.principal_department_by = newVal.DepartmentId;
                            $dialogScope.data.principal_department_name = newVal.DepartmentName;
                            $dialogScope.data.principal_area_by = newVal.BUGUID;
                            $dialogScope.data.principal_area_name = newVal.BUName;
                            $dialogScope.data.principal_name = newVal.UserName;
                        }
                        // formatResult: formatRepo,
                        // formatSelection: formatRepoSelection // omitted for brevity, see the source of this page
                };


            }


            /**
             * 判断查询时间
             * @param a
             * @param b
             * @returns {boolean}
             */
            var compareDate = function(a, b) {
                var arrA = a.split("-");
                var start = new Date(arrA[0], arrA[1], arrA[2]);
                var startTime = start.getTime();

                var arrB = b.split("-");
                var end = new Date(arrB[0], arrB[1], arrB[2]);
                var endTime = end.getTime();

                if (startTime > endTime) {
                    return true
                } else {
                    return false
                }
            };

            $scope.addContractPrincipal = function($data, $dialog, $dialogScope) {
                $scope.principals.push($.extend({
                    __type: 'add'
                }, $data));
            };
            $scope.saveContractPrincipal = function($data, $dialog, $dialogScope) {
                var start = $dialogScope.data.principal_on,
                    end = $dialogScope.data.principal_end;


                if (end && end != '' && compareDate(start, end)) {
                    utils.alert('截止时间不能超过生效时间!')
                    return false;
                }


                angular.extend($dialogScope.oldPrinp, $.extend({
                    __type: 'update'
                }, $data));

            };
            $scope.delPrincipal = function(proj) {
                /**
                 * 删除
                 */
                utils.confirm('确定要删除此合同主责人吗？', {
                    ok: function() {
                        angular.extend(proj, {
                            __type: 'delete'
                        });
                        $scope.$applyAsync();
                    }
                });

            };


            //监听合同性质
            $scope.$watch('contractBaseInfo.contract_property_id', function(newData) {
                if (newData) {
                    if (newData == notShowPrincipalByContractArr[0] || newData == notShowPrincipalByContractArr[1]) {
                        $scope.showPrincipal = false;
                    } else {
                        $scope.showPrincipal = true;
                    }
                }
            })


            $scope.$watch('contractBaseInfo.sign_amount', function(newData) {
                if ($scope.contractBaseInfo.sign_amount != myMath.add($scope.contractBaseInfo.delivery_amount, $scope.contractBaseInfo.rent_amount)) {
                    $scope.contractBaseInfo.delivery_amount = myMath.sub($scope.contractBaseInfo.sign_amount, $scope.contractBaseInfo.rent_amount);
                }
            });
            $scope.$watch('contractBaseInfo.rent_amount', function(newData) {
                if ($scope.contractBaseInfo.sign_amount != myMath.add($scope.contractBaseInfo.delivery_amount, $scope.contractBaseInfo.rent_amount)) {
                    $scope.contractBaseInfo.delivery_amount = myMath.sub($scope.contractBaseInfo.sign_amount, $scope.contractBaseInfo.rent_amount);
                }
            });
            $scope.$watch('contractBaseInfo.delivery_amount', function(newData) {
                if ($scope.contractBaseInfo.sign_amount != myMath.add($scope.contractBaseInfo.delivery_amount, $scope.contractBaseInfo.rent_amount)) {
                    $scope.contractBaseInfo.rent_amount = myMath.sub($scope.contractBaseInfo.sign_amount, $scope.contractBaseInfo.delivery_amount);
                }
            });

            //检测 生成合同编号
            $scope.$watch('contractBaseInfo.customer_id', function(newVal) {
                $scope.generalContractCode();
            });
            $scope.$watch('contractBaseInfo.area_code', function(newVal) {
                $scope.generalContractCode();
            });
            $scope.$watch('contractBaseInfo.sign_people_department_by', function(newVal) {
                $scope.generalContractCode();
            });
            $scope.generalContractCode = function() {
                if ($scope.contractBaseInfo.customer_code && $scope.contractBaseInfo.area_code) {
                    contractCommonService.genContractFlowCode($scope.contractBaseInfo.area_code, $scope.contractBaseInfo.customer_code,
                        $scope.contractBaseInfo.contract_code,
                        function(data) {
                            $scope.contractBaseInfo.contract_code = data;
                            $scope.$applyAsync();
                        });
                }
            };


            $scope.save = function() {
                /**
                 * 保存
                 */
                var isNew = contractId ? false : true;
                //合同性质为明源签约-直属区域, 云客签约-直属区域时,合同主责人必填
                var needPrincipalsByContractArr = ['54f8a2b7-fce7-11e4-bed8-00155d02c832', '7f83719a-fce8-11e4-bed8-00155d02c832'];


                //复选框数组转换成字符串
                $scope.contractBaseInfo.attribute_name = $scope.attribute_name_arr.toString();

                //收集合同信息
                var baseInfo = $scope.contractBaseInfo;
                var projectsInfo = $scope.projects;
                var principalInfo = $scope.principals;


                if (baseInfo.contract_property_id == needPrincipalsByContractArr[0] || baseInfo.contract_property_id == needPrincipalsByContractArr[1]) {
                    if (principalInfo.length <= 0) {
                        utils.alert('合同性质为 明源签约-直属区域 / 云客签约-直属区域 时, 合同主责人必填!')
                        return false;
                    }
                }


                var post_data = {
                    contract: baseInfo,
                    product: projectsInfo,
                    principal: principalInfo
                };
                var url;
                if (isNew) {
                    url = api_prefix + "/contract/add-contract";
                } else {
                    url = api_prefix + "/contract/update-contract";
                }

                utils.myAjax({
                    url: url,
                    type: "POST",
                    context: this,
                    data: post_data,
                    success: function(json) {
                        if (json.retCode === "0") {
                            if (isNew) {
                                $location.path("base").search({
                                    id: json.data
                                });
                                contractId = json.data;
                                setTimeout(function() {
                                    side.refresh();
                                }, 1000);
                                utils.alert('合同创建成功', {
                                    ok: function() {
                                        setTimeout(function() {
                                            side.refresh();
                                        }, 500);
                                    }
                                });
                            } else {
                                utils.alert("保存成功");
                            }

                            $scope.loadContract(contractId);

                        } else {
                            utils.alert("保存失败：" + json.errMsg);
                        }
                    }
                });
            };

            $scope.verify = function() {
                /**
                 * 提交复核
                 */

            }
        }]);
});
